package com.museum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.museum.entity.DO.Permission;
import com.museum.entity.DTO.Meta;
import com.museum.entity.DTO.permission.PermissionShow;
import com.museum.mapper.PermissionMapper;
import com.museum.service.api.PermissionServiceAPI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LB
 * @version 1.0
 * @date 2020/12/27 17:39
 */
@Component
public class PermissionServiceImpl implements PermissionServiceAPI {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Permission queryPermissionById(int permissionId) {
        return permissionMapper.selectOne(
                new QueryWrapper<Permission>().eq("permission_id", permissionId)
        );

    }

    /**
     * @param
     * @return
     * @Desciption 遍历树形权限菜单
     */
    @Override
    public List<PermissionShow> build(List<Permission> permissionList) {
        List<PermissionShow> listShow = new ArrayList<>();
        for (Permission permission : permissionList) {
            PermissionShow permissionShow = new PermissionShow();
            BeanUtils.copyProperties(permission, permissionShow);
            permissionShow.setMeta(new Meta(permission.getIcon(), permission.getName()));
            listShow.add(permissionShow);
        }
        List<PermissionShow> trees = new ArrayList<>();
        for (PermissionShow permissionShow : listShow) {
            if (permissionShow.getParentId().equals(0)) {
                trees.add(findChilds(permissionShow, listShow));
            }
        }
        return trees;
    }

    private PermissionShow findChilds(PermissionShow permissionShow, List<PermissionShow> listShow) {
        for (PermissionShow show : listShow) {
            if (show.getParentId().equals(permissionShow.getPermissionId())) {
                permissionShow.getChildren().add(findChilds(show, listShow));
            }
        }
        return permissionShow;
    }
}
